package base_05_reflect;

import java.lang.reflect.Field;

/**
 * 反射之Field类
 *
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2022, 广州九尾信息科技有限公司
 * @date 2022/3/24 18:15
 */
public class FieldDemo {
    private String name;
    private int age;
    private User user;

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, InstantiationException {
        Class<FieldDemo> clazz = FieldDemo.class;
        FieldDemo instance = clazz.newInstance();
        System.out.println(">>>>>>>>>>>>>>>>>>getFields>>>>>>>>>>>>>>>>>");
        Field[] fields = clazz.getFields();
        for (Field field : fields) {
            System.out.print(" 字段名：" + field.getName());
            System.out.println(" 字段类型：" + field.getType());
        }
        System.out.println(">>>>>>>>>>>>>>>>>>getDeclaredFields>>>>>>>>>>>>>>>>>");
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields) {
            System.out.println("字段类型：" + field.getType());
        }
        System.out.println(">>>>>>>>>>>>>>>>>>getDeclaredField>>>>>>>>>>>>>>>>>");
        //通过字段变量名称获取public权限Field
        Field f1 = clazz.getDeclaredField("age");
        System.out.println(f1.getType());
        f1.set(instance, 11);
        System.out.println(instance.age);
        Class<User> uClass = User.class;
        User user = uClass.newInstance();
        //getField能获取父类public字段
        Field name = uClass.getDeclaredField("name");
        name.setAccessible(true);
        name.set(user,"名字");
        Field f2 = uClass.getField("age");
        f2.set(user, 22);
        f2.setInt(user,33);
        System.out.println(user.age);

    }

}

class User extends Parent {
    private String name;
}

class Parent {
    public int age;
}
